<template>
  <div class="dashboard-container">
    <div class="app-top">
      <el-card shadow="never">
        <!-- 从学科进入 :  面包屑 -->
        <el-breadcrumb v-if="$route.query.name" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
          <br />
          <hr />
          <br />
        </el-breadcrumb>
        <el-form ref="topform" :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="目录名称">
            <el-input v-model="form.directoryName" placeholder></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.state" placeholder="请选择">
              <el-option v-for="item in status" :key="item.id" :label="item.state" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="clear">清除</el-button>
            <el-button type="primary" @click="search">搜索</el-button>
          </el-form-item>
          <el-button
            class="newAdd"
            icon="el-icon-back"
            type="text"
            @click="ret"
            v-if="$route.query.id"
          >返回学科</el-button>
          <el-button class="newAdd" icon="el-icon-edit" type="success" @click="addRole">新增目录</el-button>
        </el-form>
        <el-alert :title="`数据一共${total}条`" type="info" show-icon :closable="false"></el-alert>
        <!-- 新增目录的弹框 -->
        <!-- 新增弹框 -->
        <el-dialog
          :title="roleForm.id ? '修改目录' : '新增目录'"
          :visible="roleDialogVisible"
          @close="closeDialog"
        >
          <!-- 表单内容 -->
          <el-form
            ref="roleForm"
            :model="roleForm"
            :rules="rules"
            label-width="100px"
            v-if="Object.keys($route.query).length===0"
          >
            <el-form-item label="所属学科" prop="subjectID">
              <el-select v-model="roleForm.subjectID" style="width:80%" placeholder="请选择">
                <!-- label:文案  value:选中哪个哪个的value会被自动绑定到select v-model后面的属性上 一般和后端交互 提交给后端 -->
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.subjectID"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="目录名称" prop="directoryName">
              <el-input v-model="roleForm.directoryName" style="width:80%" placeholder="请输入目录名称" />
            </el-form-item>
          </el-form>
          <el-form
            ref="roleForm"
            :model="roleForm"
            :rules="rules"
            label-width="100px"
            v-if="Object.keys($route.query).length!==0"
          >
            <el-form-item label="目录名称" prop="directoryName">
              <el-input v-model="roleForm.directoryName" style="width:80%" placeholder="请输入目录名称" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-button size="small" @click="closeDialog">取消</el-button>
            <el-button size="small" type="primary" @click="confirm">确定</el-button>
          </el-row>
        </el-dialog>
        <el-table :data="list" style="width: 100%; margin-top: 20px">
          <el-table-column type="index" prop="date" label="序号" width="50" />
          <el-table-column prop="subjectName" label="所属学科" width="180" />
          <el-table-column prop="directoryName" label="目录名称" width="180" />
          <el-table-column prop="username" label="创建者" />
          <el-table-column prop="addDate" label="创建日期">
            <template #default="{row}">{{ formatDate(row.addDate) }}</template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量" />
          <el-table-column prop="state" label="状态">
            <template #default="{row}">{{ formatState(row.state) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{row}">
              <el-button type="text" @click="changeState(row)">{{ row.state === 1 ? "启用" : "禁用" }}</el-button>
              <el-button type="text" :disabled="row.state === 1" @click="revise(row)">修改</el-button>
              <el-button type="text" :disabled="row.state === 1" @click="remove(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="params.page"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="params.pagesize"
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          background
          @size-change="sizeChange"
          @current-change="pageChange"
        ></el-pagination>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list as getCompanys } from "@/api/hmmm/companys";
import { list as getQuestion } from "@/api/hmmm/questions";
import {
  list,
  remove,
  add,
  update,
  changeState
} from "@/api/hmmm/directorys.js";
import dayjs from "dayjs";

export default {
  created() {
    getCompanys();
    getQuestion();
    // 刷新数据
    this.getDirectorys();
  },
  data() {
    return {
      form: {
        directoryName: "",
        state: ""
      },
      roleForm: {
        directoryName: "",
        subjectID: ""
      },
      list: [],
      roleDialogVisible: false,
      total: 0,
      state: null,
      params: {
        page: 1, // 当前页
        pagesize: 10 // 每页条数
      },
      rules: {
        subjectID: [
          { required: true, message: "请选择所属学科", trigger: "blur" }
        ],
        directoryName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
          { min: 1, max: 8, message: "目录名称要求1-8个字符", trigger: "blur" }
        ]
      },
      // 状态格式转化
      formatState(value) {
        const TYPE = {
          0: "已启用",
          1: "已禁用"
        };
        return TYPE[value];
      },
      status: [
        { id: 0, state: "启用" },
        { id: 1, state: "禁用" }
      ]
    };
  },
  methods: {
    // 分页
    // 当前页
    pageChange(page) {
      // console.log(`当前页: ${page}`);
      this.params.page = page;
      this.getDirectorys();
    },
    // 每页条数
    sizeChange(pagesize) {
      this.params.pagesize = pagesize;
      this.getDirectorys();
    },
    // 初始化数据
    async getDirectorys() {
      let res = "";
      if (this.$route.query.id) {
        this.params.subjectID = this.$route.query.id;
        res = await list(this.params);
        this.list = res;
      } else {
        res = await list(this.params);
      }
      // console.log(res)
      this.total = res.data.counts;
      this.list = res.data.items;
      // this.params.pagesize = res.pagesize
      // console.log(list)
    },
    // 清除
    clear() {
      this.form = {
        name: "",
        state: ""
      };
      this.getDirectorys()
      delete this.params.state
      delete this.params.directoryName
      // console.log(delete this.params.state);

    },
    // 时间格式化
    formatDate(value, str = "YYYY-MM-DD") {
      return dayjs(value).format(str);
    },
    // 控制 禁用启用按钮
    async changeState(row) {
      try {
        this.state = row.state === 1 ? 0 : 1;
        await changeState({ id: row.id, state: this.state });
        this.getDirectorys();
        this.$message.success("操作成功");
      } catch (error) {
        console.log(error);
      }
    },
    // 删除
    async remove(scoped) {
      this.$confirm("确定要删除吗?", "温馨提示")
        .then(async () => {
          await remove(scoped);
          this.getDirectorys();
          this.$message.success("删除成功");
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 新增目录
    addRole() {
      this.roleDialogVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.roleDialogVisible = false;
      this.roleForm = {
        directoryName: "",
        subjectID: ""
      };
      this.$refs.roleForm.resetFields();
    },
    // 兜底校验
    confirm() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          if (this.roleForm.id) {
            await update(this.roleForm);
          } else {
            if (this.$route.query.id) {
              this.roleForm.subjectID = +this.$route.query.id;
              await add(this.roleForm);
            } else {
              await add(this.roleForm);
            }
          }
          this.$message.success(`${this.roleForm.id ? "修改成功" : "添加成功"}`);
          // 刷新数据
          this.getDirectorys();
          // 关闭弹窗
          this.closeDialog();
        }
      });
    },
    //  修改目录
    async revise(row) {
      this.roleDialogVisible = true;
      const {data: res} = await list(row);
      console.log(res.items[0])
      const newData = res.items[0];
      this.roleForm = newData;
    },
    // 搜索功能
    async search() {
      if ((this.form.directoryName || this.form.state) === "") {
        this.getDirectorys();
      } else if (this.form.directoryName === "") {
        this.params.state = this.form.state;
      } else if (this.form.state === "") {
        this.params.directoryName = this.form.directoryName;
      } else {
        this.params.directoryName = this.form.directoryName;
        this.params.state = this.form.state;
      }
      this.params.page = 1;
      this.getDirectorys();
    },
    // 返回学科
    ret() {
      window.history.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
.app-top {
  padding: 11px;
}
.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
.newAdd {
  // margin-left: 400px;
  height: 35px;
}

.el-pagination {
  text-align: right;
  margin-top: 20px;
}
</style>
